//
//  GKDYPlayerViewController.m
//  GKDYVideo
//
//  Created by QuintGao on 2018/9/23.
//  Copyright © 2018 QuintGao. All rights reserved.
//

#import "GKDYPlayerViewController.h"
#import "GKSlidePopupView.h"
#import "GKBallLoadingView.h"
#import "GKLikeView.h"
#import "GKDYVideoScrollView.h"
#import "GKDYVideoCell.h"
#import "GKDYPlayerManager.h"
#import "GKDYVideoPortraitCell.h"
#import "AFNetworking.h"
#import "WSPlayerRequest.h"
#import "CTMediator+WSPlayerAction.h"

@interface GKDYPlayerViewController ()<GKDYPlayerManagerDelegate>
@property (nonatomic, strong) GKDYPlayerManager * manager;
@property (nonatomic, strong) WSPlayerRequest * request;
@end

@implementation GKDYPlayerViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
    [self setupRefresh];
    [self requestData];
}

- (void)dealloc {
    NSLog(@"playerVC dealloc");
}

- (void)initUI {
    self.view.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.manager.scrollView];
    [self.manager.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
}

- (void)setupRefresh {
    WeakSelf
    self.manager.scrollView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestMoreData:nil];
    }];
}

- (void)requestData {
    GKBallLoadingView *loadingView = [GKBallLoadingView loadingViewInView:self.view];
    [loadingView startLoading];
    [self requestData:^{
        [loadingView stopLoading];
        [loadingView removeFromSuperview];
    }];
}

- (void)refreshData:(charonTV_EmptyBlock)completion {
    [self requestData:completion];
}

- (void)requestData:(charonTV_EmptyBlock)completion {
    WeakSelf
    [self.request refreshDataSuccess:^(NSArray *array) {
        [weakSelf loadSuccessWithArray:array isRefresh:YES];
        !completion ?: completion();
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        [weakSelf loadFailedWithError:error];
        !completion ?: completion();
    }];
}

- (void)requestMoreData:(charonTV_EmptyBlock)completion {
    WeakSelf
    self.request.loading = YES;
    [self.request loadMoreDataSuccess:^(NSArray *array) {
        [weakSelf loadSuccessWithArray:array isRefresh:NO];
        !completion ?: completion();
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        [weakSelf loadFailedWithError:error];
        !completion ?: completion();
    }];
}

- (void)loadSuccessWithArray:(NSArray *)array isRefresh:(BOOL)isRefresh {
    WeakSelf;
    if ([weakSelf respondsToSelector:@selector(requestData:)]) {
        if (isRefresh) {
            [weakSelf.manager.dataSources removeAllObjects];
        }
        [weakSelf.manager.dataSources addObjectsFromArray:array];
        if (isRefresh) {
            [self.manager.scrollView reloadData];
        }
        else  {
            weakSelf.manager.scrollView.defaultIndex = self.manager.scrollView.currentIndex;
            [weakSelf.manager.scrollView reloadData];
        }
        [weakSelf.manager.scrollView.mj_header endRefreshing];
        [weakSelf.manager.scrollView.mj_footer endRefreshing];
        [weakSelf loadCompleteWithArray:array];
    }
}

- (void)loadCompleteWithArray:(NSArray *)array {
    WeakSelf;
    weakSelf.manager.scrollView.mj_footer.hidden = array.count <= 0;
    if(weakSelf.request.haveMore) {
        [weakSelf.manager.scrollView.mj_footer resetNoMoreData];
        weakSelf.manager.scrollView.mj_footer.hidden = YES;
    }
    else {
        [weakSelf.manager.scrollView.mj_footer endRefreshingWithNoMoreData];
        weakSelf.manager.scrollView.mj_footer.hidden = NO;
    }
}

- (void)loadFailedWithError:(NSError *)error {
    WeakSelf;
    [weakSelf.manager.scrollView.mj_header endRefreshing];
    [weakSelf.manager.scrollView.mj_footer endRefreshing];
    // 隐藏当前的上拉刷新控件
    weakSelf.manager.scrollView.mj_footer.hidden = !weakSelf.request.haveMore || weakSelf.manager.dataSources.count == 0;
    [self analysisError:error];
}

// 解析失敗、無顯示网络
- (void)analysisError:(NSError *)error {
    if (error.code == NSURLErrorNotConnectedToInternet || error.code == NSURLErrorCannotDecodeContentData) {
        /// 网络异常
        [WSToast simple:APPLocalized(@"網絡異常")];
    }
    else if (error.code == NSURLErrorBadServerResponse || (error.code > 1000)) {
        /// 服务器無响应
        [WSToast simple:APPLocalized(@"服務器無響應")];
    }
    else {
        /// 其他問題
        [WSToast simple:error.localizedDescription];
    }
}

- (void)likecharonTV_Request:(WSVideo *)model {
    [WSPlayerRequest favoritecharonTV_WithChapter_id:model.id tv_id:model.tv_id success:^{
        model.isLike = YES;
        model.like_num ++;
        if (self.model.id == model.id) {
            self.manager.currentCell.portraitView.model = model;
        }
    } failed:^(NSURLResponse * _Nonnull response, NSError * _Nonnull error, id  _Nonnull responseObject) {
        
    }];
}

- (WSVideo *)model {
    return self.manager.currentCell.model;
}

- (void)openChapterMenuWithModel:(WSVideo *)model {
    WeakSelf
    UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_ChapterListWithVideo:model selectHandle:^(id obj) {
        UIViewController * target = [[CTMediator sharedInstance]ct_showcharonTV_PlayerWithVideo:obj];
        [weakSelf.navigationController pushViewController:target animated:YES];
    }];
    target.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    target.modalPresentationStyle = UIModalPresentationCustom;
    [self presentViewController:target animated:YES completion:nil];
}

#pragma mark - JXCategoryListContentViewDelegate
- (UIView *)listView {
    return self.view;
}

- (void)listDidAppear {
    self.manager.isAppeared = YES;
    [self.manager play];
}

- (void)listWillDisappear {
    [self.manager pause];
}

- (void)listDidDisappear {
    self.manager.isAppeared = NO;
}

#pragma mark - GKDYPlayerManagerDelegate
- (void)cellDidClickLike:(WSVideo *)model {
    [self likecharonTV_Request:model];
}

- (void)cellDidClickChapter:(WSVideo *)model {
    [self openChapterMenuWithModel:model];
}
#pragma mark - 懒加载
- (GKDYPlayerManager *)manager {
    if (!_manager) {
        _manager = [[GKDYPlayerManager alloc] init];
        _manager.delegate = self;
        _manager.isPlayNext = YES;
    }
    return _manager;
}

- (WSPlayerRequest *)request {
    if (!_request) {
        _request = [WSPlayerRequest new];
    }
    return _request;
}
@end
